package demo1;

public class MyQueue {
    static class ListNode{
        private final int val;
        private ListNode next;
        private ListNode prev;

        private ListNode(int val) {
            this.val = val;
        }
    }
    public ListNode first;
    public ListNode last;

    /**
     * 入队操作：尾插法
     * @param val
     */
    public void offer(int val) {
        ListNode node = new ListNode(val);
        if(empty()) {
            first = last = node;
        }
        last.next = node;
        node.prev = last;
        last = last.next;
    }

    /**
     * 出队操作：删除头节点
     * @return
     */
    public int poll() {
        if(empty()) {
            return -1;
        }
        int value = first.val;
        if(first == last) {
            first = last = null;
            return value;
        }else {
            first = first.next;
            first.prev = null;
            return first.val;
        }
    }

    /**
     * 获得头节点不删除
     * @return
     */
    public int peek() {
        if(empty()) {
            return -1;
        }
        return first.val;
    }

    /**
     * 获得有效数据
     * @return
     */
    public int size() {
        ListNode cur = first;
        int usedSize = 0;
        while (cur != null) {
            usedSize++;
            cur = cur.next;
        }
        return usedSize;
    }

    /**
     * 判断是否为空
     * @return
     */
    public boolean empty() {
        return first == null;
    }
}
